package com.nest.WorkNest.act;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.lidroid.xutils.exception.HttpException;
import com.nest.WorkNest.R;
import com.nest.WorkNest.api.XutilsPost;
import com.nest.WorkNest.config.UserInfo;
import com.nest.WorkNest.entity.User;
import com.nest.WorkNest.tools.Tool;
import com.nest.WorkNest.tools.Utils;

import org.json.JSONObject;

//登录
public class LoginAct extends BaseActivity implements OnClickListener {
    private TextView tv_skip, tv_forgetpwd;
    private EditText et_telphone, et_password;
    private Button btn_login;
    private String telphone, password;
    private Context context = LoginAct.this;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.act_login);
        showStatusBar();
        Intent intent = getIntent();
        initBar();
        initProgress(context, "正在登录...");
        actionbar_side_name.setVisibility(View.VISIBLE);
        actionbar_side_name.setText("登录");
        initView();
        actionbar_side_name.setVisibility(View.VISIBLE);
        ll_tv_actionbar_side_right.setVisibility(View.VISIBLE);
        tv_actionbar_side_right.setText("注册");
        if (!(intent.getExtras() == null)) {
            getIntentBundle();
        }
        manager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);

    }

    public void initView() {
        tv_skip = (TextView) findViewById(R.id.tv_loginact_skip);
        tv_forgetpwd = (TextView) findViewById(R.id.tv_loginact_forgetpwd);
        et_telphone = (EditText) findViewById(R.id.edtTxt_loginact_telphone);
        et_password = (EditText) findViewById(R.id.edtTxt_loginact_password);
        btn_login = (Button) findViewById(R.id.btn_loginact_login);
        btn_login.setOnClickListener(this);
        ll_tv_actionbar_side_right.setOnClickListener(this);
        tv_skip.setOnClickListener(this);
        tv_forgetpwd.setOnClickListener(this);
    }

    public void getIntentBundle() {
        Bundle bundle = getIntent().getExtras();
        telphone = bundle.getString("telphone");
        password = bundle.getString("password");
        et_telphone.setText(telphone);
        // et_password.setText(password);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            // 登录
            case R.id.btn_loginact_login:
                initLogin();
                break;
            case R.id.ll_tv_actionbar_side_right:
                startActivity(new Intent(context, RegisterAct.class));
                break;
            case R.id.tv_loginact_skip:
                startActivity(new Intent(context, MainTabAct.class));
                fileHelper.putInt(UserInfo.USER_ID, -1);
                fileHelper.putString(UserInfo.TEL_PHONE, "");
                fileHelper.putString(UserInfo.PASSWORD, "");
                this.finish();
                break;
            case R.id.tv_loginact_forgetpwd:
                startActivity(new Intent(context, PwdBackAct.class));
                break;
        }
    }

    private void initLogin() {
        telphone = et_telphone.getText().toString().trim();
        password = et_password.getText().toString().trim();
        User user = new User();
        user.setTelPhone(telphone);
        user.setPassword(password);
        XutilsPost xutilsPost = new XutilsPost();
        XutilsPost.IOAuthCallBack ioAuthCallBack = new XutilsPost.IOAuthCallBack() {
            @Override
            public void getIOAuthCallBack(String result) {
                JSONObject jsonObject = Tool.getJsonObject(result);
                if (Tool.getString(jsonObject, "resultCode").equals("0")) {
                    String token = Tool.getString(jsonObject, "token");
                    fileHelper.putShareProf("", "");
                    fileHelper.putInt(UserInfo.USER_ID, 1);
                    fileHelper.putString(UserInfo.TEL_PHONE, telphone);
                    fileHelper.putString(UserInfo.PASSWORD, password);
                    fileHelper.putString(UserInfo.TOKEN, token);
                    fileHelper.putBoolean(UserInfo.USERINFO_ISLOGIN, true);
                    startActivity(new Intent(context, MainTabAct.class));
                    finish();
                    showToast("登录成功");
                } else if (Tool.getString(jsonObject, "resultCode").equals("9002")) {
                    showToast("用户不存在");
                } else if (Tool.getString(jsonObject, "resultCode").equals("9004")) {
                    showToast("密码错误");
                }
                if (pd.isShowing())
                    pd.cancel();
            }

            @Override
            public void getDealException(HttpException httpException, String result) {
                if (pd.isShowing())
                    pd.cancel();
            }

            @Override
            public void getLoadingCallBack(long total, long current, boolean isUploading) {
                if (!pd.isShowing())
                    pd.show();
            }
        };
        if (TextUtils.isEmpty(telphone)) {
            showToast("手机号不能为空");
        } else if (TextUtils.isEmpty(password)) {
            showToast("密码不能为空");
        } else if (!Utils.ismobiles(telphone)) {
            showToast("请输入正确手机号");
        } else if (Utils.ismobiles(telphone)) {
            xutilsPost.doPostLogin(context, user, ioAuthCallBack);
        }

    }


    private void showStatusBar() {
        WindowManager.LayoutParams attrs = getWindow().getAttributes();
        attrs.flags &= ~WindowManager.LayoutParams.FLAG_FULLSCREEN;
        getWindow().setAttributes(attrs);
    }

    public boolean onTouchEvent(MotionEvent event) {
        try {
            if (event.getAction() == MotionEvent.ACTION_DOWN) {
                if (getCurrentFocus() != null && getCurrentFocus().getWindowToken() != null) {
                    manager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(),
                            InputMethodManager.HIDE_NOT_ALWAYS);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return super.onTouchEvent(event);
    }
}
